package org.execute.tool.adsPower;

import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AdspowerStart {
    private final String apiKey;
    private final List<String> profileIds;
    private AdspowerClient client;
    private AdspowerBrowserManager manager;

    // 构造方法：初始化API密钥和批量配置ID列表
    public AdspowerStart(String apiKey, List<String> profileIds) {
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new IllegalArgumentException("API密钥不能为空");
        }
        if (profileIds == null || profileIds.isEmpty()) {
            throw new IllegalArgumentException("配置ID列表不能为空");
        }
        this.apiKey = apiKey;
        this.profileIds = new ArrayList<>(profileIds); // 防御性拷贝
    }

    public static void main(String[] args) {
        // 1. 配置批量处理的参数
        String apiKey = "d1063d2be44322da692d508314f7b08b"; // 替换为实际API密钥
        List<String> profileIds = new ArrayList<>();
        profileIds.add("k14xrtue");       // 配置ID1
        profileIds.add("k150015t");   // 配置ID2（替换为实际ID）

        // 2. 实例化批量处理器并执行
        AdspowerStart batchProcessor = new AdspowerStart(apiKey, profileIds);
        try {
            batchProcessor.processBatch();
        } catch (Exception e) {
            System.err.println("批量处理失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 批量处理主流程
     */
    /**
     * 批量处理主流程（修复连接池关闭问题）
     */
    public void processBatch() throws IOException {
        // 1. 手动管理客户端生命周期，不在try-with-resources中自动关闭
        AdspowerClient client = new AdspowerClient(apiKey);
        AdspowerBrowserManager manager = new AdspowerBrowserManager(client);

        try {
            // 2. 批量启动浏览器
            Map<String, Map<String, Object>> launchResults = manager.startBrowserList(profileIds);
            System.out.println("批量启动结果: " + launchResults);

            // 3. 处理每个配置
            for (Map.Entry<String, Map<String, Object>> entry : launchResults.entrySet()) {
                String profileId = entry.getKey();
                Map<String, Object> result = entry.getValue();

                if (result.containsKey("error")) {
                    System.err.println("配置 " + profileId + " 启动失败: " + result.get("error"));
                    continue;
                }

                processSingleProfile(profileId, result);
            }
        } finally {
            // 4. 所有操作完成后，先关闭浏览器，再关闭客户端
            closeAllBrowsers(manager); // 显式传入manager，确保使用未关闭的client
            client.close(); // 最后关闭连接池
            System.out.println("API客户端已关闭");
        }
    }
    /**
     * 处理单个配置的业务逻辑
     * @param profileId 配置ID
     * @param launchResult 启动结果
     */
    private void processSingleProfile(String profileId, Map<String, Object> launchResult) {
        WebDriver driver = null;
        AdsPowerWebAction webAction = null;

        try {
            // 解析启动结果中的调试信息
            Map<String, Object> data = (Map<String, Object>) launchResult.get("data");
            JSONObject jsonData = new JSONObject(data);

            // 配置WebDriver
            System.setProperty("webdriver.chrome.driver", jsonData.getString("webdriver"));
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption(
                    "debuggerAddress",
                    jsonData.getJSONObject("ws").getString("selenium")
            );
            driver = new ChromeDriver(options);
            webAction = new AdsPowerWebAction(driver);

            // 执行核心操作
            System.out.println("\n===== 开始处理配置: " + profileId + " =====");
            webAction.navigateTo("https://www.baidu.com");
            System.out.println("[" + profileId + "] 页面标题: " + webAction.getPageTitle());

            String screenshotPath = webAction.takeScreenshot();
            System.out.println("[" + profileId + "] 截图保存至: " + screenshotPath);

            webAction.waitMillis(3000); // 等待观察
            System.out.println("[" + profileId + "] 处理完成");

        } catch (Exception e) {
            System.err.println("[" + profileId + "] 处理异常: " + e.getMessage());
        } finally {
            // 关闭当前配置的WebDriver
            if (webAction != null) {
                webAction.quitBrowser();
            }
        }
    }

    /**
     * 关闭所有浏览器（使用传入的manager，确保client未关闭）
     */
    private void closeAllBrowsers(AdspowerBrowserManager manager) {
        if (manager == null) return;

        for (String profileId : profileIds) {
            try {
                manager.stopBrowser(profileId); // 此时client仍未关闭，可正常发送请求
                System.out.println("[" + profileId + "] 浏览器已关闭");
            } catch (IOException e) {
                System.err.println("[" + profileId + "] 关闭失败: " + e.getMessage());
            }
        }
    }
}